/**
 * React Hook for Room State Manager
 * 提供响应式的房间状态管理
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import { roomStateManager } from '../utils/RoomStateManager';
import type { RoomStateUpdate } from '../utils/RoomStateManager';
import { RoomStatus } from '../../../types/room';

export interface UseRoomStateManagerReturn {
  // 状态查询
  getRoomStatus: (roomId: string, date: string) => RoomStatus | null;

  // 状态更新
  setRoomStatus: (roomId: string, date: string, status: RoomStatus) => void;
  batchUpdateStatus: (updates: RoomStateUpdate[]) => void;

  // 批量查询
  getRoomStatesInRange: (
    roomId: string,
    startDate: string,
    endDate: string
  ) => Map<string, RoomStatus>;
  findRoomsByStatus: (status: RoomStatus, date: string) => string[];

  // 统计信息
  getStatistics: (date: string) => Record<RoomStatus, number>;

  // 数据管理
  clearRoomStatus: (roomId: string, date?: string) => void;
  exportAllStates: () => Record<string, Record<string, RoomStatus>>;
  importStates: (data: Record<string, Record<string, RoomStatus>>) => void;

  // 响应式状态
  lastUpdate: number;
  isLoading: boolean;
}

/**
 * 房间状态管理Hook
 */
export const useRoomStateManager = (): UseRoomStateManagerReturn => {
  const [lastUpdate, setLastUpdate] = useState<number>(Date.now());
  const [isLoading, setIsLoading] = useState<boolean>(false);

  // 订阅状态变更
  useEffect(() => {
    const unsubscribe = roomStateManager.subscribe(
      (updates: RoomStateUpdate[]) => {
        console.log('🔄 房间状态更新:', updates);
        setLastUpdate(Date.now());
      }
    );

    return unsubscribe;
  }, []);

  // 获取房间状态
  const getRoomStatus = useCallback(
    (roomId: string, date: string): RoomStatus | null => {
      return roomStateManager.getRoomStatus(roomId, date);
    },
    []
  );

  // 设置房间状态
  const setRoomStatus = useCallback(
    (roomId: string, date: string, status: RoomStatus): void => {
      roomStateManager.setRoomStatus(roomId, date, status);
    },
    []
  );

  // 批量更新状态
  const batchUpdateStatus = useCallback((updates: RoomStateUpdate[]): void => {
    setIsLoading(true);
    try {
      roomStateManager.batchUpdateStatus(updates);
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 获取房间在日期范围内的状态
  const getRoomStatesInRange = useCallback(
    (roomId: string, startDate: string, endDate: string) => {
      return roomStateManager.getRoomStatesInRange(roomId, startDate, endDate);
    },
    []
  );

  // 按状态查找房间
  const findRoomsByStatus = useCallback(
    (status: RoomStatus, date: string): string[] => {
      return roomStateManager.findRoomsByStatus(status, date);
    },
    []
  );

  // 获取统计信息
  const getStatistics = useCallback((date: string) => {
    return roomStateManager.getStatistics(date);
  }, []);

  // 清除房间状态
  const clearRoomStatus = useCallback((roomId: string, date?: string): void => {
    roomStateManager.clearRoomStatus(roomId, date);
  }, []);

  // 导出所有状态
  const exportAllStates = useCallback(() => {
    return roomStateManager.exportAllStates();
  }, []);

  // 导入状态
  const importStates = useCallback(
    (data: Record<string, Record<string, RoomStatus>>): void => {
      setIsLoading(true);
      try {
        roomStateManager.importStates(data);
      } finally {
        setIsLoading(false);
      }
    },
    []
  );

  return useMemo(
    () => ({
      getRoomStatus,
      setRoomStatus,
      batchUpdateStatus,
      getRoomStatesInRange,
      findRoomsByStatus,
      getStatistics,
      clearRoomStatus,
      exportAllStates,
      importStates,
      lastUpdate,
      isLoading,
    }),
    [
      getRoomStatus,
      setRoomStatus,
      batchUpdateStatus,
      getRoomStatesInRange,
      findRoomsByStatus,
      getStatistics,
      clearRoomStatus,
      exportAllStates,
      importStates,
      lastUpdate,
      isLoading,
    ]
  );
};

/**
 * 房间状态缓存Hook - 用于优化大量房间的状态查询
 */
export const useRoomStateCache = (roomIds: string[], dates: string[]) => {
  const { getRoomStatus, lastUpdate } = useRoomStateManager();

  const cachedStates = useMemo(() => {
    const cache = new Map<string, RoomStatus | null>();

    roomIds.forEach(roomId => {
      dates.forEach(date => {
        const key = `${roomId}-${date}`;
        const status = getRoomStatus(roomId, date);
        cache.set(key, status);
      });
    });

    return cache;
  }, [roomIds, dates, getRoomStatus, lastUpdate]);

  const getCachedStatus = useCallback(
    (roomId: string, date: string): RoomStatus | null => {
      const key = `${roomId}-${date}`;
      return cachedStates.get(key) || null;
    },
    [cachedStates]
  );

  return {
    getCachedStatus,
    cacheSize: cachedStates.size,
    lastUpdate,
  };
};

export default useRoomStateManager;
